<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input type="text" name="sn" placeholder="序列号(SN)" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <select id="appSelect" name="appName" placeholder="应用" lay-filter="appSelect">
                                    <option value="" selected></option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <select id="funcSelect" name="funcName" placeholder="功能" lay-filter="funcSelect">
                                    <option value="" selected></option>
                                </select>
                            </div>


                        </div>
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input type="text" name="terminalType" placeholder="型号" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <select name="status" placeholder="启停状态">
                                <option value="" selected></option>
                                <option value="0">停用</option>
                                <option value="1">启用</option>
                            </select>

                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbar">
            <div class="layui-btn-group">
                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="add">
                    <i class="layui-icon">新增</i>
                </button>
                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="import">
                    <i class="layui-icon">导入</i>
                </button>
                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="batchEnable">
                    <i class="layui-icon">启用</i>
                </button>
                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="batchDisable">
                    <i class="layui-icon">停用</i>
                </button>
<!--                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="delete">-->
<!--                    <i class="layui-icon">&#xe640;删除</i>-->
<!--                </button>-->
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-xs layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>

            {{# if(d.status==1) { }}
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="disable">停用</a>
            {{# } }}
            {{# if(d.status==0 || d.status == null) { }}
            <a class="layui-btn layui-btn-xs layui-btn-xs data-count-edit" lay-event="enable">启用</a>
            {{# } }}

        </script>

    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        const host = `${window.location.protocol}//${window.location.host}`;
        $.ajaxSetup({
            headers: {'Access-Token': sessionStorage.getItem('token'), 'userId': sessionStorage.getItem("userId")}
        });
        table.render({
            title: '终端设备列表',
            elem: '#currentTableId',
            method: 'get',
            url: `${host}/terminal/page`,
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                {type: "checkbox", width: 50, fixed: 'left'},
                {field: 'sn', width: 180, title: '序列号(SN)', fixed: 'left'},
                {field: 'orgName', width: 130, title: "机构",align: 'center', fixed: 'left'},
                {field: 'terminalType', width: 120, title: '型号',align: 'center', fixed: 'left'},
                {field: 'activeStatus', width: 100, title: '终端状态',align: 'center',fixed: 'left', templet: (d) => {
                        return d.activeStatus === 1 ? '已激活' : '未激活';
                    }
                },
                {field: 'status', width: 100, title: '启停状态',align: 'center', fixed: 'left', templet: (d) => {
                        return 1 === d.status ? "<font style='color:green'>启用</font>" : "<font style='color:red'>停用</font>";
                    }},
                {field: 'activeReqTime', width: 200, title: '最近连接时间',align: 'center', fixed: 'left'},

                {field: 'appName', width: 180, title: '应用',align: 'center'},
                {field: 'funcName', width: 180, title: '功能',align: 'center'},
                {field: 'position', width: 180, title: '位置',align: 'center'},
                {field: 'activeTime', width: 160, title: '激活时间',align: 'center'},
                {field: 'expiryTime', width: 160, title: '有效截止时间',align: 'center'},
                {field: 'expiryType', width: 120, title: '有效期类型',align: 'center', templet: (d) => {
                        if ("01" === d.expiryType) {
                            return "1个月";
                        } else if ("03" === d.expiryType) {
                            return "3个月";
                        } else if ("06" === d.expiryType) {
                            return "6个月";
                        } else if ("12" === d.expiryType) {
                            return "12个月";
                        } else if ("24" === d.expiryType) {
                            return "24个月";
                        } else if ("P" === d.expiryType) {
                            return "永久有效";
                        }
                    }
                },
                {field: 'appVer', width: 120, title: '应用版本号',align: 'center'},
                {field: 'funcVer', width: 120, title: '功能版本',align: 'center'},
                // {field: 'addType', width: 120, title: '添加方式',align: 'center', templet: (d) => {
                //         if ('manual' === d.addType) {
                //             return "手动";
                //         } else if ('import' === d.addType) {
                //             return "导入";
                //         }
                //     }},
                {field: 'createTime', width: 180, title: '创建时间',align: 'center'},
                {title: '操作', fixed: 'right', minWidth: 180, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line',
            parseData: (rest) => {
                return {
                    "code": rest.code,
                    "msg" : rest.msg,
                    "count" : rest.data.total,
                    "data" : rest.data.records
                }
            },
            request: {
                pageName: 'current',
                limitName: 'size'
            }
        });

        // 加载应用搜索框搜索数据原
        $.get(`${host}/app/selectList`, (rest) => {
            if (rest.code === "00") {
                $.each(rest.data, function (index, item) {
                    let option = new Option(item.text, item.value);
                    $('#appSelect').append(option);
                });
            }
            form.render("select");
        });

        form.on('select(appSelect)', (data) => {
            $('#funcSelect').empty();
            $('#funcSelect').append(new Option("", ""));
            $.get(`${host}/func/selectList`,{'appId': data.value}, (rest) => {
                if (rest.code === "00") {
                    $.each(rest.data, function (index, item) {
                        let option = new Option(item.text, item.value);
                        $('#funcSelect').append(option);
                    });
                }
                form.render("select");
            });
        })

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            //执行搜索重载
            table.reload('currentTableId', {
                page: { current: 1 },
                where: { 'searchParams' : result }
            }, 'data');
            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '新增',
                    btn: ['确定','关闭'],
                    type: 2,
                    shade: 0.2,
                    maxmin:false,
                    shadeClose: false,
                    area: ['80%', '80%'],
                    content: `add.html?timestamp=${new Date().getTime()}`,
                    yes : (index, layero) => {
                        let addData = $(layero).find('iframe')[0].contentWindow.callbackData();
                        $.post(`${host}/terminal/save`, addData, (rest) => {
                            if (rest && "00" === rest.code) {
                                layer.msg(rest.msg);
                                table.reload("currentTableId");
                                layer.close(index);
                            } else {
                                layer.msg(rest.msg);
                            }
                        });
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'import') {
                 let importModel = layer.open({
                    title: '导入',
                    btn: ['确定','关闭'],
                    type: 2,
                    shade: 0.2,
                    maxmin:false,
                    shadeClose: false,
                    area: ['80%', '80%'],
                    content: `import/index.html?timestamp=${new Date().getTime()}`,
                    yes : (index, layero) => {
                        let addData = $(layero).find('iframe')[0].contentWindow.callbackData();
                        $.post(`${host}/terminal/save`, addData, (rest) => {
                            if (rest && "00" === rest.code) {
                                layer.msg(rest.msg);
                                table.reload("currentTableId");
                                layer.close(index);
                            } else {
                                layer.msg(rest.msg);
                            }
                        });
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                let checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
            } else if (obj.event === 'batchEnable') {
                let checkStatus = table.checkStatus('currentTableId') , rows = checkStatus.data;
                if (0 === rows.length) {
                    layer.msg("至少选择一项");
                    return false;
                }

                let ids = [];
                for (let index in rows) {
                    let row = rows[index];
                    if (row.status === 1) {
                        layer.msg("选择数据中存在已启用设备");
                        return false;
                    }
                    ids.push(row.id);
                }
                layer.confirm('是否确定启用', function (index) {
                    $.post("/terminal/enable", {'ids': ids.join(",")}, (rest) => {
                        layer.msg(rest.msg);
                        if (rest && "00" === rest.code) {
                            $(".layui-laypage-btn")[0].click();
                        }
                    })
                });
            } else if (obj.event === 'batchDisable') {
                let checkStatus = table.checkStatus('currentTableId') , rows = checkStatus.data;
                if (0 === rows.length) {
                    layer.msg("至少选择一项");
                    return false;
                }
                let ids = [];
                for (let index in rows) {
                    let row = rows[index];
                    if (row.status === 1) {
                        layer.msg("选择数据中存在已停用设备");
                        return false;
                    }
                    ids.push(row.id);
                }
                layer.confirm('是否确定停用', function (index) {
                    $.post("/terminal/disable", {'ids': ids.join(",")}, (rest) => {
                        layer.msg(rest.msg);
                        if (rest && "00" === rest.code) {
                            $(".layui-laypage-btn")[0].click();
                        }
                    })
                });
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') {
                var index = layer.open({
                    title: '修改',
                    btn: ['确定','关闭'],
                    type: 2,
                    shade: 0.2,
                    maxmin:false,
                    shadeClose: false,
                    area: ['80%', '80%'],
                    content: `edit.html?timestamp=${new Date().getTime()}`,
                    success: (layero, index) => {
                        var body = layer.getChildFrame('body', index);
                        body.find('input[name="id"]').val(obj.data.id);
                        body.find('input[name="appId"]').val(obj.data.appId);
                        body.find('input[name="funcId"]').val(obj.data.funcId);
                        body.find('input[name="appName"]').val(obj.data.appName);
                        body.find('input[name="funcName"]').val(obj.data.funcName);
                        body.find('input[name="sn"]').val(obj.data.sn);
                        body.find('input[name="terminalType"]').val(obj.data.terminalType);
                        body.find('select[name="expiryType"]').val(obj.data.expiryType);

                        body.find('input[name="position"]').val(obj.data.position);

                        body.find('input[name="appId"]').click();
                    },
                    yes : (index, layero) => {
                        let editData = $(layero).find('iframe')[0].contentWindow.callbackData();
                        $.post("/terminal/save", editData, (rest) => {
                            if (rest && "00" === rest.code) {
                                layer.msg(rest.msg);
                                $(".layui-laypage-btn")[0].click();
                                layer.close(index);
                            } else {
                                layer.msg(rest.msg);
                            }
                        });
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                if (1 === obj.data.activeStatus) {
                    layer.msg("设备已激活，不能删除");
                    return false;
                }

                layer.confirm('是否确定删除', function (index) {
                    let id = obj.data.id;
                    $.post("/terminal/delete", {'id': id}, (rest) => {
                        layer.msg(rest.msg);
                        if (rest && "00" === rest.code) {
                            obj.del();
                        }
                    })
                    layer.close(index);
                });
            } else if (obj.event === 'disable') {
                if (0 === obj.data.status) {
                    layer.msg("设备已停用");
                    return false;
                }

                layer.confirm('是否确定停用', function (index) {
                    let id = obj.data.id;
                    $.post("/terminal/disable", {'ids': id}, (rest) => {
                        layer.msg(rest.msg);
                        if (rest && "00" === rest.code) {
                            $(".layui-laypage-btn")[0].click();
                        }
                    })
                });
            } else if (obj.event === 'enable') {
                if (1 === obj.data.status) {
                    layer.msg("设备已启用");
                    return false;
                }

                layer.confirm('是否确定启用', function (index) {
                    let id = obj.data.id;
                    $.post("/terminal/enable", {'ids': id}, (rest) => {
                        layer.msg(rest.msg);
                        if (rest && "00" === rest.code) {
                            $(".layui-laypage-btn")[0].click();
                        }
                    })
                });
            }
        });
    });
</script>

</body>
</html>